<?php

class Halls_Thumb_UploadAction extends SrsHallsBaseAction
{
  public function isSecure()
  {
    return false;
  }

	public function executeWrite(AgaviRequestDataHolder $rd)
	{
		/* @var $rd AgaviWebRequestDataHolder */
    if (!$rd->hasFile('image'))
    {
      return 'Error';
    }

    $hall = Doctrine_Query::create()
            ->from('Hall')
            ->where('id=?', array($rd->getParameter('id', 0)))
            ->fetchOne();

    if ($hall === null)
    {
      return 'Error';
    }

    /* @var $file AgaviUploadedFile */
    $file = $rd->getFile('image');

    $dest = AgaviConfig::get('core.uploads_dir') . '/halls/' . $hall->id;

    $fileName = $this->createFileName($file);

    if (empty($fileName))
    {
      return 'Error';
    }

    $imageFile = $dest . '/' . $fileName;

    if (!$file->move($imageFile))
    {
      return 'Error';
    }

    WideImage::loadFromFile($imageFile)->resizeDown(640, 480)->saveToFile($imageFile);
    WideImage::loadFromFile($imageFile)->resizeDown(200, 150)->saveToFile($thumbFile = $this->createThumbFileName($imageFile));

    $this->setAttribute('image', $fileName);
    $this->setAttribute('hall', $hall);

    return 'Success';
	}

  private function createFileName(AgaviUploadedFile $file)
  {
    $name = substr(md5(uniqid(microtime())), 0, 8);
    $ext  = strrchr($file->getName(), '.');

    return in_array($ext, array('.gif', '.jpg', '.png')) ? $name . $ext : null;
  }

  private function createThumbFileName($imageFile)
  {
    $pos = strrpos($imageFile, '/') + 1;

    return substr($imageFile, 0, $pos) . 'thumb_' . substr($imageFile, $pos);
  }
}